<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of MailingPage
 *
 * @author juwking
 */
class MailingPage extends PageController {

    private $page;

    function __construct() {
        parent::__construct();
    }

    function getPageName() {
        return 'mailing';
    }

    public function Next() {
        $this->page++;
    }

    public function getPage() {
        return $this->page;
    }

    public function Previous() {
        $this->page--;
        $this->assign('pageNum', $this->page);
    }

    public function getTemplate() {
        return "mailing/mailingMain.tpl";
    }

    public function getSidebar() {
        $sidebar = array(
            array(label => 'Przygotuj wiadomość', link => 'createMailing'),
            array(label => 'Przygotuj kolejke', link => 'createQue'),
            array(label => 'Generuj', link => 'randomClients'),
            array(label => 'Generuj', link => 'randomClients')
        );
        return $sidebar;
    }

    public function createMailing() {
        $this->smarty->display('mailing/mailingTinyTCE.tpl');
    }

    public function createQue() {
        $message = MessageQuery::create()->setFormatter(ModelCriteria::FORMAT_ARRAY)->find();

        $this->assign('content', 'mailing/queCreator.tpl');
        foreach ($message as $key => $value) {
            $messageArray[$key] = $value;
            #$messageArray[$key]['message_content'] = $this->readMessage($value->getMessagePath());
            $messageArray[$key]['message_content'] = $this->readMessage($value['MessagePath']);
        }
        $this->assign('messages', $messageArray);
        $this->smarty->display('mailing/queCreator.tpl');
    }

    public function createQue2($page=null) {

        if (!isset($_SESSION['grid'])) {
            $_SESSION['grid'] = new AjaxGrid();
        }
        //$ajaxGrid->setData($pager);
        $_SESSION['grid']->display();
    }

    public function createQue3() {
        var_dump($_SESSION['createdMessage']);
    }

    public function updateTarget() {
        $_SESSION['createdMessage']->updateTarget($_REQUEST['Target']);
    }

    public function prepareMessage() {
        $_SESSION['createdMessage'] = new MailingQueClass($_REQUEST['MessageId']);
    }

    private function readMessage($filename) {
        $fh = fopen($filename, 'r');
        $theData = fread($fh, filesize($filename));
        fclose($fh);
        return $theData;
    }

    public function saveMessage() {
        $filename = "./messages/" . rand() . '.txt';
        $fp = fopen($filename, 'w');
        fwrite($fp, $_REQUEST['message']);
        fclose($fp);
        $message = new MessageQuery();

        $message->Insert(array('message_users_id' => $_SESSION['UserAccess']["users_id"], 'message_path' => $filename, 'message_mail_type_id' => 1));
        $this->assign('content', $this->getContent());
    }

}

?>
